#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import logging
import traceback

from public.util import get_next_value

import unittest


class BasicProxy(object):
    def get_proxy(self, extra=None):
        pass


class RdsProxy(BasicProxy):
    def __init__(self, rds):
        self.rds = rds

    def get_proxy(self, extra=None):
        proxy = None
        if self.rds is None:
            return proxy
        try:
            idx_key = extra['proxy_idx']
            hash_key = extra['proxy_hash']
            lock_prefix = extra['proxy_lock_prefix']
            lock_sec = extra['proxy_lock_sec']
            lock_step = extra.get('proxy_lock_step', 3)
            max_limit = extra.get('proxy_max_limit', 180)
            proxy = get_next_value(self.rds, idx_key, hash_key, lock_prefix, lock_sec, lock_step, max_limit)
            proxies = {"http": proxy, "https": proxy}
        except Exception as e:
            logging.error(e)
            logging.error(traceback.format_exc())
            return proxy
        return proxies


class SquidProxy(BasicProxy):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.proxy = '{0}:{1}'.format(host, port)
        # self.proxies = {"http": self.proxy, "https": self.proxy}          # python3.6以前用
        self.proxies = {"http": "http://" + self.proxy, "https": "https://" + self.proxy}         # Python3.6以后用

    def get_proxy(self, extra=None):
        return self.proxies


class TestProxy(unittest.TestCase):
    def test_squid(self):
        host = '127.0.0.1'
        port = 8888
        spx = SquidProxy(host, port)
        proxy = spx.get_proxy()
        url = 'http://127.0.0.1:8888'
        r = requests.get(url, proxies=proxy, timeout=5)
        print('\n\n{0}'.format(r.text))
        self.assertEqual(r.status_code, 200)


if __name__ == '__main__':
    unittest.main()
